<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix process-header flex width100p">
        <div class="title flex-auto">
          {{ processTitle }}<span class="ml10 sub-title">{{ subTitle }}</span>
        </div>
        <div class="btn-list flex flex-row align-center mr20">
          <div class="pl15 pr15">
            上报人：<span class="primary-color">{{
              processStructureValue.workOrder.createdName
            }}</span>
          </div>
          <div class="pl15 pr15" style="margin-right:250px">
            最新状态：<span class="primary-color">{{
              processStructureValue.workOrder.current_state_name
            }}</span>
            <span v-if="processStructureValue.workOrder.principals != ''" class="ml20">当前处理人：</span>
            <span v-if="processStructureValue.workOrder.principals != ''" class="danger-color">【{{
                processStructureValue.workOrder.principals }}】</span>
          </div>
          <div class="flex fixed-btn bg-white" style="right: 30px;">
            <el-button type="" size="mini" class="mr10" @click="backPage">
              返 回
            </el-button>
            <template v-for="(item, index) in processStructureValue.edges">
              <el-button
                v-if="processStructureValue.workOrder.is_end === 0 &&
                  item.source === currentNode.id
                "
                :key="index"
                size="mini"
                type="primary"
                @click="handelRemark(item)"
              >
                {{ item.label }}
              </el-button>
            </template>
            <!-- <el-button type="primary" size="mini" @click="handlePrint(printData)">
              导出PDF
            </el-button> -->
          </div>
        </div>
      </div>
      <el-dialog
        width="40%"
        title=""
        custom-class="techDialog"
        :visible.sync="remarkVisible"
        :modal="false"
        :close-on-click-modal="false"
        append-to-body
      >
        <div slot="title" class="clearfix mt30 flex flex-row">
          <div class="font16 width110 pt3 text-right mr10">处置意见</div>
          <el-input
            v-model="remarks"
            type="textarea"
            class="width80p"
            placeholder="请输入处置意见"
            maxlength="200"
            :autosize="{ minRows: 5, maxRows: 99 }"
            show-word-limit
          />
        </div>
        <div v-if="showNextSec" class="clearfix flex flex-row align-center">
          <div class="font16 width110 text-right mr10">{{ repeatAssign ? '再分配给部门' : '分配给部门' }}</div>
          <el-select v-model="leaderID" filterable multiple placeholder="" size="small" style="width: 50%">
            <el-option v-for="(item, index) in users" :key="index" :label="item.deptName" :value="item.userId">
              <!-- <span style="float: left">{{ item.nickName }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.deptName
              }}</span> -->
              <span style="float: left">{{ item.nickName }}</span>

            </el-option>
          </el-select>
        </div>
        <div slot="footer">
          <div class="btn-list mr50">
            <template v-for="(item, index) in processStructureValue.edges">
              <el-button
                v-if="processStructureValue.workOrder.is_end === 0 &&
                  item.source === currentNode.id &&
                  item.label == currentFlowProperties
                "
                :key="index"
                size="mini"
                type="primary"
                @click="submitAction(item)"
              >
                {{ item.label }}
              </el-button>
            </template>
          </div>
        </div>
      </el-dialog>
      <div class="flex">
        <div class="right width300 ml10">
          <el-card class="box-card history-box mb20 history-baqsj">
            <div slot="header" class="clearfix flex flex-row align-center height32">
              <div class="line" />
              <span class="font16 ml10 flex-auto">审批历史</span>
            </div>
            <vue-scroll :ops="ops">
              <div class="timeline">
                <el-timeline v-if="timelineShow">
                  <el-timeline-item
                    v-for="item in timeLine"
                    :key="item.id"
                    :hide-timestamp="true"
                    icon="el-icon-my-time"
                    color="#277fd6"
                    size="large"
                  >
                    <div class="flex flex-column">
                      <div class="time">
                        <span class="text">{{ item.create_time }}</span>
                        <el-tag :type="getHistoryTag(item)" effect="dark" size="small" class="stateTag ml10">
                          {{ getHistoryState(item) }}
                        </el-tag>
                      </div>
                      <div v-if="item.status == 2 && item.target != ''" class="info">
                        <span class="label">上报人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div v-else class="info">
                        <span class="label">审批人：</span><span class="detail">{{ item.processor }}</span>
                      </div>
                      <div class="info">
                        <span class="label">审批节点：</span><span class="detail">{{ item.state }}</span>
                      </div>
                      <div v-if="item.status == 2 && item.target != ''" class="info flex flex-row" />
                      <div v-else class="info flex flex-row">
                        <span class="label">处置意见：</span><span class="detail flex-auto">{{
                          formatFullMessage(item.remarks)
                        }}</span>
                      </div>
                      <div v-if="getModifyText(item.remarks)" class="info flex flex-row">
                        <span class="label">分配部门：</span><span class="detail flex-auto">{{
                          getModifyText(item.remarks)
                        }}</span>
                      </div>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div v-else class="empty-time mt100">
                  <img src="@/assets/empty.png" alt="">
                  <span>暂时没有审批内容</span>
                </div>
              </div>
            </vue-scroll>
          </el-card>
        </div>
      </div>
    </el-card>
<!--    <require-dialog ref="requireDialog" :type="requireValue" @changeRequireStr="changeRequireStr" />-->
  </div>
</template>
<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import { processStructure, handleWorkOrder } from '@/api/baqsj/work-order'
import { createDisposeTpl } from '@/api/process/dispose-tpl'
import { listAllUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList, bqDeptList } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import printJS from 'print-js'
import { getDuration } from '@/utils/costum'
import { mergeAndDedupeArrays } from '@/utils/index'
import { formatFullMessage, getModifyText } from '@/utils/format'
export default {
  name: 'BaqsjHandle',
  components: {
  },
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formatFullMessage,
      getModifyText,
      mergeAndDedupeArrays,
      repeatAssign: false,
      lastDisposeIds: [],
      bqTrees: [],
      getDuration,
      models: {
        suspectedDrug: [],
        togetherDrug: [],
        ypblfygc: ''
      },
      zfsplRadio: {
        '0': '数周内',
        '1': '一年数次',
        '2': '1-2年1次',
        '3': '2-5年1次',
        '4': '五年以上'
      },
      shjgRadio: {
        '0': '死亡',
        '1': '极重度',
        '2': '重度',
        '3': '中度',
        '4': '轻度',
        '5': '轻微/无伤害'
      },
      sjlxOptions: [
        {
          label: '诊疗相关',
          value: '诊疗相关'
        },
        {
          label: '药物相关',
          value: '药物相关'
        },
        {
          label: '医疗器械相关',
          value: '医疗器械相关'
        },
        {
          label: '医患沟通相关',
          value: '医患沟通相关'
        },
        {
          label: '输血相关',
          value: '输血相关'
        },
        {
          label: '护理相关',
          value: '护理相关'
        },
        {
          label: '院感相关',
          value: '院感相关'
        },
        {
          label: '手术相关',
          value: '手术相关'
        },
        {
          label: '防保相关',
          value: '防保相关'
        },
        {
          label: '意外事件',
          value: '意外事件'
        },
        {
          label: '其他不良事件上报',
          value: '其他不良事件上报'
        }
      ],
      sjflOptions: [],
      sjflDefaultOptions: [
        {
          label: '医疗处置事件',
          value: '医疗处置事件'
        },
        {
          label: '报告、标本差错事件',
          value: '报告、标本差错事件'
        },
        {
          label: '饮食差错事件',
          value: '饮食差错事件'
        },
        {
          label: '输液反应事件',
          value: '输液反应事件'
        },
        {
          label: '其他不良事件',
          value: '其他不良事件'
        },
        {
          label: '药物不良反应事件',
          value: '药物不良反应事件'
        },
        {
          label: '给药错误事件',
          value: '给药错误事件'
        },
        {
          label: '医疗器械事件',
          value: '医疗器械事件'
        },
        {
          label: '医患沟通（纠纷）事件',
          value: '医患沟通（纠纷）事件'
        },
        {
          label: '用血错误事件',
          value: '用血错误事件'
        },
        {
          label: '输血反应事件',
          value: '输血反应事件'
        },
        {
          label: '护理相关事件',
          value: '护理相关事件'
        },
        {
          label: '院内感染不良事件',
          value: '院内感染不良事件'
        },
        {
          label: '手术不良事件',
          value: '手术不良事件'
        },
        {
          label: '操作不良事件',
          value: '操作不良事件'
        },
        {
          label: '非计划再次手术事件',
          value: '非计划再次手术事件'
        },
        {
          label: '职业暴露不良事件',
          value: '职业暴露不良事件'
        },
        {
          label: '跌倒、坠床事件',
          value: '跌倒、坠床事件'
        },
        {
          label: '出走事件',
          value: '出走事件'
        },
        {
          label: '冲动伤人事件',
          value: '冲动伤人事件'
        },
        {
          label: '噎食事件',
          value: '噎食事件'
        },
        {
          label: '自杀、自伤事件',
          value: '自杀、自伤事件'
        },
        {
          label: '其他意外事件',
          value: '其他意外事件'
        },
        {
          label: '公共事件',
          value: '公共事件'
        },
        {
          label: '治安事件',
          value: '治安事件'
        },
        {
          label: '其他事件',
          value: '其他事件'
        }
      ],
      models: {
        suspectedDrug: [],
        togetherDrug: [],
        ypblfygc: ''
      },
      requireValue: {},
      formOptions: [],
      list3: [],
      sjpg_slot_form: {
        sjpg_sjfl: '',
        sjpg_shjg: '',
        sjpg_shjg_text: '',
        sjpg_zfspl: '',
        sjpg_zfspl_text: '',
        sjpg_sac: '',
        sjpg_sjlx: '',
        cz_yhjysyg: [],
        cz_ywpysyg: []
      },
      currentFlowProperties: null,
      showNextSec: false,
      processTitle: '',
      subTitle: '',
      processId: '',
      nextUserId: 0,
      leaderID: [],
      timelineShow: false,
      timeLine: [],
      users: [],
      handleUserMap: {},
      ops: {
        vuescroll: {
          mode: 'native',
          sizeStrategy: 'percent',
          detectResize: true,
          locking: true
        },
        scrollPanel: {
          maxHeight: 800
        },
        bar: {
          background: '#277fd6',
          size: '3px',
          keepShow: true
        },
        rail: {
          background: '#E0E8F0',
          opacity: 1,
          size: '3px',
          specifyBorderRadius: false,
          gutterOfEnds: '50px',
          gutterOfSide: '0px',
          keepShow: false
        }
      },
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      limitTechList: [],
      selectLimitData: [],
      remarkVisible: false,
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      isLoadingStatus: true,
      currentNode: {
        hideTpls: null,
        writeTpls: null
      },
      isActiveProcessing: false,
      tpls: [],
      remarks: '', // 备注信息
      alertMessage: '',
      nodeStepList: [],
      newTpls: [],
      circulationHistoryList: [],
      activeIndex: 0,
      processStructureValue: {
        workOrder: { title: '' }
      },
      ruleForm: {
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        self_data: {},
        state_id: '',
        state: '',
        source_state: '',
        is_assign: 0,
        processor: '',
        process_method: '',
        tpls: [],
        tasks: []
      },
      processId: null,
      workOrderId: null,
      topnum: '',
      bottomnum: '',
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        },
        async bqTreeList(resolve) {
          const res = await bqDeptList()
          resolve(res.data)
        }
      }
    }
  },
  watch: {
    'sjpg_slot_form.sjpg_shjg': function(newVal) {
      this.sjpg_slot_form.sjpg_shjg_text = this.shjgRadio[newVal]
      console.log(this.sjpg_slot_form.sjpg_shjg_text)
      this.calculateScore()
    },
    'sjpg_slot_form.sjpg_zfspl': function(newVal) {
      this.sjpg_slot_form.sjpg_zfspl_text = this.zfsplRadio[newVal]
      console.log(this.sjpg_slot_form.sjpg_zfspl_text)
      this.calculateScore()
    }
  },
  computed: {
    ...mapGetters(['name', 'userId'])
  },
  async created() {
    this.showNextSec = false
    this.nextUserId = 0
    this.leaderID = []
    this.processId = parseInt(this.$route.query.processId)
    this.ruleForm.workOrderId = parseInt(this.$route.query.workOrderId)
    this.workOrderId = parseInt(this.$route.query.workOrderId)
    await this.getBqTreeList()
    this.getProcessNodeList()
  },
  methods: {
    async getBqTreeList() {
      const res = await bqDeptList()
      if (res.data) {
        this.bqTrees = res.data
      }
    },
    calculateScore() {
      const sacMatrix = [
        [1, 1, 1, 1, 2],
        [1, 1, 2, 2, 3],
        [2, 2, 2, 3, 3],
        [3, 3, 3, 4, 4],
        [3, 4, 4, 4, 4],
        [4, 4, 4, 4, 4]
      ]
      this.sjpg_slot_form.sjpg_sac =
        sacMatrix[this.sjpg_slot_form.sjpg_shjg][
          this.sjpg_slot_form.sjpg_zfspl
          ]
    },
    changeRequireStr(str) {
      this.models.ypblfygc = this.models.ypblfygc + str
    },
    requireDialogClick(value) {
      this.requireValue = value
      this.$refs.requireDialog.open(value)
    },
    openDrug() { },
    addDrugRow(type) {
      const id = new Date().getTime()
      console.log(type)
      this.models[type].push({
        num: id,
        approvalNum: '',
        name: '',
        niversalName: '',
        dosageFrom: '',
        prodFactory: '',
        prodBatch: '',
        dosage: '',
        dosageUnit: '',
        dosageDay: '',
        dosageRate: '',
        drugRoute: '',
        startDate: '',
        endDate: '',
        reason: ''
      })
    },
    delSuspectedDrug(row, type) {
      const index = this.models[type].findIndex(item => item.num === row.num)
      if (index > -1) {
        this.models[type].splice(index, 1)
        this.list3.splice(this.list3.indexOf(row.drugId), 1)
      }
    },
    changeModels(num, selectDosage, type) {
      const list = this.models[type]
      if (list && list.length > 0) {
        list.forEach(item => {
          if (item.num === num) {
            item.dosageFrom = selectDosage.join(',')
          }
        })
      }
      this.models[type] = JSON.parse(JSON.stringify(list))
    },
    changeSjlx(val) {
      this.sjpg_slot_form.sjpg_sjfl = ''
      if (val == '诊疗相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(0, 5)
      } else if (val == '药物相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(5, 7)
      } else if (val == '医疗器械相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(7, 8)
      } else if (val == '医患沟通相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(8, 9)
      } else if (val == '输血相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(9, 11)
      } else if (val == '护理相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(11, 12)
      } else if (val == '院感相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(12, 13)
      } else if (val == '手术相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(13, 16)
      } else if (val == '防保相关') {
        this.sjflOptions = this.sjflDefaultOptions.slice(16, 17)
      } else if (val == '意外事件') {
        this.sjflOptions = this.sjflDefaultOptions.slice(17, 23)
      } else if (val == '其他不良事件上报') {
        this.sjflOptions = this.sjflDefaultOptions.slice(23, 26)
      }
    },
    getHistoryState(item) {
      if (item.circulation == '结束') {
        return '审批完成'
      } else if (item.circulation == '已撤回') {
        return '已撤回'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return '提交上报'
          } else {
            return '转交'
          }
        } else if (item.status == 0) {
          return '审批退回'
        } else {
          return '审批通过'
        }
      }
    },
    getHistoryTag(item) {
      if (item.circulation == '结束') {
        return 'success'
      } else if (item.circulation == '已撤回') {
        return 'danger'
      } else {
        if (item.status == 2) {
          if (item.target != '') {
            return ''
          } else {
            return 'warning'
          }
        } else if (item.status == 0) {
          return 'danger'
        } else {
          return 'success'
        }
      }
    },

    handlePrint(params) {
      printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })
    },
    backPage() {
      this.$router.push({ path: '/baqsj/upcoming', query: {}})
    },
    async handelRemark(item) {
      const app = this
      const target = item.target
      let nextNode

      for (var nodeItem of this.processStructureValue.nodes) {
        if (target == nodeItem.id) {
          nextNode = nodeItem
        }
      }
      console.log(nextNode)
      if (item.label == '再分配') {
        this.repeatAssign = true
      }
      if (item.label == '分派职能部门' || item.label == '再分配') {
        this.showNextSec = true
      } else {
        this.showNextSec = false
      }

      var promiseList = []
      if (item.label != '不相关' && item.label != '退回') {
        if (item.label != '分派职能部门') {
          console.log(this.sjpg_slot_form)
          if (
            !this.sjpg_slot_form.sjpg_sjlx ||
            !this.sjpg_slot_form.sjpg_sjfl ||
            !this.sjpg_slot_form.sjpg_shjg_text ||
            !this.sjpg_slot_form.sjpg_zfspl_text ||
            !this.sjpg_slot_form.sjpg_sac
          ) {
            if (
              this.processStructureValue.workOrder.current_state_name ==
              '医务科反馈'
            ) {
              this.$messageS({
                type: 'error',
                message: '请完善事件评估'
              })

              app.$nextTick(() => {
                const el = document.querySelectorAll('.sjpgbd')[0]
                el.scrollIntoView({ block: 'center', behavior: 'smooth' })
              })
              return false
            }
          }
        }
        if ((this.processStructureValue.workOrder.processName ==
          '药物不良反应事件' &&
          this.processStructureValue.workOrder.current_state_name ==
          '医务科处置中'
        ) || (this.processStructureValue.workOrder.processName ==
          '医疗器械事件' &&
          this.processStructureValue.workOrder.current_state_name ==
          '医务科处置中'
        )) {
          for (var tpl of this.processStructureValue.tpls) {
            promiseList.push(
              this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
            )
          }
        } else {
          for (var tpl of this.processStructureValue.tpls) {
            promiseList.push(this.$refs['generateForm-' + tpl.id][0].getData())
          }
        }

        Promise.all(promiseList).then(values => {
          for (var valItem of values) {
            // 适配老的处置表单
            if (
              valItem.hasOwnProperty('cz_yglysyg') &&
              item.label != '分派职能部门'
            ) {
              console.log(valItem)
              if (
                !this.validArray(valItem.cz_yglysyg) &&
                !this.validArray(valItem.cz_ygzryysyg) &&
                !this.validArray(valItem.cz_yhzysyg) &&
                !this.validArray(this.sjpg_slot_form.cz_yhjysyg) &&
                !this.validArray(this.sjpg_slot_form.cz_yhjysyg) &&
                !this.sjpg_slot_form.cz_yhjysyg_input1 &&
                !this.sjpg_slot_form.cz_yhjysyg_input2 &&
                !this.sjpg_slot_form.cz_ywpysyg_input1 &&
                !this.sjpg_slot_form.cz_ywpysyg_input2
              ) {
                this.$messageS({
                  type: 'error',
                  message: '请至少选择一项原因分析'
                })
                app.$nextTick(() => {
                  const el = document.querySelectorAll('.czbd')[0]
                  el.scrollIntoView({ block: 'center', behavior: 'smooth' })
                })
                return
              }
            }
            // 适配新的处置表单的原因分析
            if (
              valItem.hasOwnProperty('cz_ybrysxg') &&
              item.label == '处置'
            ) {
              console.log(valItem)
              if (
                !this.validArray(valItem.cz_ybrysxg) &&
                !this.validArray(valItem.cz_ygtxgys) &&
                !this.validArray(valItem.cz_yyggrysxg) &&
                !this.validArray(valItem.cz_yyqssysxg) &&
                !this.validArray(valItem.cz_ygzztlcsjxg) &&
                !valItem.cz_qtysxg
              ) {
                this.$messageS({
                  type: 'error',
                  message: '请至少选择一项原因分析'
                })
                return
              }
            }
          }
          this.remarkVisible = true
        })
      } else {
        this.remarkVisible = true
      }
      this.currentFlowProperties = item.label
    },
    validArray(val) {
      if (val && val.length > 0) {
        return true
      }
      return false
    },

    getProcessNodeList() {
      processStructure({
        processId: this.processId,
        workOrderId: this.workOrderId
      }).then(response => {
        this.isActiveProcessing = false
        this.processStructureValue = response.data
        this.newTpls = response.data.tpls
        this.circulationHistoryList = this.processStructureValue.circulationHistory
        this.subTitle = this.processStructureValue.process.name
        this.processTitle = this.processStructureValue.process.category

        if (this.processStructureValue.workOrder.current_state_name ==
          '职能部门处置中') {
          for (let tplV2Tmp = 0; tplV2Tmp < this.processStructureValue.tpls.length; tplV2Tmp++) {
            if (this.processStructureValue.tpls[tplV2Tmp].mid == 'baqsjczv3') {
              this.processStructureValue.tpls[tplV2Tmp].form_data = {
                yqssmc: '',
                yqssxlh: '',
                cz_qtysxg: '',
                cz_ybrysxg: [],
                cz_ygtxgys: [],
                cz_yyggrysxg: [],
                cz_yyqssysxg: [],
                cz_ygzztlcsjxg: [],
                showPriceTable: 1,
                text_1715438413000_72733: '5.与仪器/设施因素相关(非必填):',
                header_1694566373000_6219: '原因分析'
              }
            }
            if (this.processStructureValue.tpls[tplV2Tmp].mid == 'baqsjczqxv3') {
              this.processStructureValue.tpls[tplV2Tmp].form_data = {
                header_1694566373000_6219: '原因分析',
                cz_ybrysxg: [],
                cz_ygzztlcsjxg: [],
                cz_yyggrysxg: [],
                cz_ygtxgys: [],
                text_1715438413000_72733: '5.与仪器/设施因素相关(非必填):',
                yqssmc: '',
                yqssxlh: '',
                showPriceTable: 1,
                cz_yyqssysxg: [],
                cz_qtysxg: '',
                header_1715571811000_29040: '仅限设备科填写',
                ylqx_cpmc: '',
                ylqx_spmc: '',
                ylqx_zczh: '',
                ylqx_scgsmc: '',
                ylqx_guigexh: '',
                ylqx_cpbh: '',
                ylqx_cpph: '',
                ylqx_yxqz: '',
                ylqx_scrq: '',
                ylqx_tyrq: '',
                ylqx_zrrq: '',
                ylqx_czr: [],
                ylqx_sjcbysfx: ''
              }
            }
          }
        }

        for (var itemTpl of this.newTpls) {
          if (itemTpl.form_data.hasOwnProperty('sjpg_shjg')) {
            this.sjpg_slot_form.sjpg_shjg = itemTpl.form_data.sjpg_shjg
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_shjg_text')) {
            this.sjpg_slot_form.sjpg_shjg_text =
              itemTpl.form_data.sjpg_shjg_text
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_zfspl_text')) {
            this.sjpg_slot_form.sjpg_zfspl_text =
              itemTpl.form_data.sjpg_zfspl_text
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_sjfl')) {
            this.sjpg_slot_form.sjpg_sjfl = itemTpl.form_data.sjpg_sjfl
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_sjlx')) {
            this.sjpg_slot_form.sjpg_sjlx = itemTpl.form_data.sjpg_sjlx
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_zfspl')) {
            this.sjpg_slot_form.sjpg_zfspl = itemTpl.form_data.sjpg_zfspl
          }
          if (itemTpl.form_data.hasOwnProperty('sjpg_sac')) {
            this.sjpg_slot_form.sjpg_sac = itemTpl.form_data.sjpg_sac
          }
          if (itemTpl.form_data.hasOwnProperty('suspectedDrug')) {
            this.models.suspectedDrug = itemTpl.form_data.suspectedDrug
          }
          if (itemTpl.form_data.hasOwnProperty('togetherDrug')) {
            this.models.togetherDrug = itemTpl.form_data.togetherDrug
          }
          if (itemTpl.form_data.hasOwnProperty('ypblfygc')) {
            this.models.ypblfygc = itemTpl.form_data.ypblfygc
          }
        }

        if (this.circulationHistoryList.length > 0) {
          this.timelineShow = true
          this.timeLine = this.circulationHistoryList
        }
        this.ruleForm.projectNo = this.processStructureValue.workOrder.projectNo

        // 获取当前展示节点列表
        this.nodeStepList = []
        if (this.processStructureValue.nodes) {
          for (var i = 0; i < this.processStructureValue.nodes.length; i++) {
            if (
              this.processStructureValue.nodes[i].id ===
              this.processStructureValue.workOrder.current_state
            ) {
              // 当前节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
              this.activeIndex = this.nodeStepList.length - 1
              if (i + 1 === this.processStructureValue.nodes.length) {
                this.activeIndex = this.nodeStepList.length
              }
              this.currentNode = this.processStructureValue.nodes[i]
            } else if (!this.processStructureValue.nodes[i].isHideNode) {
              // 非隐藏节点
              this.nodeStepList.push(this.processStructureValue.nodes[i])
            }
          }
        }

        // 如果回退到初始节点则可编辑。
        if (this.activeIndex === 0 && this.currentNode.clazz === 'start') {
          this.currentNode.writeTpls = []
          for (var tplTmp of this.processStructureValue.tpls) {
            this.currentNode.writeTpls.push(tplTmp.form_structure.id)
          }
        }

        // 判断是否需要主动处理
        for (var stateValue of this.processStructureValue.workOrder.state) {
          if (
            this.processStructureValue.workOrder.current_state ===
            stateValue.id &&
            stateValue.processor.length > 1
          ) {
            this.isActiveProcessing = true
            break
          }

          if (stateValue.label == '职能部门处置') {
            this.lastDisposeIds = stateValue.processor
          }
        }
        this.isLoadingStatus = false
        listAllUser({ isHandle: 1 }).then(response => {
          this.users = response.data
          for (let userIndex = 0; userIndex < this.users.length; userIndex++) {
            const tmpUser = this.users[userIndex]
            this.handleUserMap[tmpUser.userId] = tmpUser.nickName
          }
        })
      })
    },
    submitAction(item) {
      var promiseList = []
      this.tpls = []
      if (!this.remarks) {
        this.$messageS({
          type: 'error',
          message: '请输入处置意见'
        })
        return false
      }

      if (this.leaderID.length == 0 && (item.label == '分派职能部门' || item.label == '再分配')) {
        this.$messageS({
          type: 'error',
          message: '请选择审批部门'
        })
        return false
      }

      // 处理分配和再分配人员的名单记录
      let assignUsers = ''
      if (this.leaderID.length > 0 && (item.label == '分派职能部门' || item.label == '再分配')) {
        const tmpNamesArr = []
        for (const assignId of this.leaderID) {
          tmpNamesArr.push(this.handleUserMap[assignId])
        }
        assignUsers = tmpNamesArr.join(',')
        this.remarks = this.remarks + '分配部门:' + assignUsers
      }

      for (var tpl of this.processStructureValue.tpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id,
          mid: tpl.mid
        })
        if (item.label != '退回' && item.label != '不相关') {
          if ((this.processStructureValue.workOrder.processName ==
              '药物不良反应事件' &&
              this.processStructureValue.workOrder.current_state_name ==
              '医务科处置中'
            ) || this.processStructureValue.workOrder.processName ==
            '医疗器械事件' &&
            this.processStructureValue.workOrder.current_state_name ==
            '医务科处置中'
          ) {
            for (var tpl of this.processStructureValue.tpls) {
              promiseList.push(
                this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
              )
            }
          } else {
            for (var tpl of this.processStructureValue.tpls) {
              promiseList.push(
                this.$refs['generateForm-' + tpl.id][0].getData()
              )
            }
          }
        }
      }
      Promise.all(promiseList).then(async values => {
        const disposeTpl = {
          work_order: parseInt(this.workOrderId)
        }
        for (const tplTmp of this.processStructureValue.tpls) {
          if (tplTmp.mid == 'baqsjczv3' || tplTmp.mid == 'baqsjczqxv3' || tplTmp.mid == 'baqsjczywv3') {
            disposeTpl.form_name = tplTmp.form_name
            disposeTpl.mid = tplTmp.mid
            disposeTpl.form_structure = tplTmp.form_structure
            disposeTpl.mobile_form_structure = tplTmp.mobile_form_structure
            disposeTpl.creator = this.userId
            disposeTpl.creator_name = this.name
          }
        }
        for (var tplDataIndex in this.tpls) {
          if (
            this.tpls[tplDataIndex].mid == 'baqsjpg'
          ) {
            values[tplDataIndex] = {
              ...values[tplDataIndex],
              ...this.sjpg_slot_form
            }
          }
          if (this.tpls[tplDataIndex].mid == 'baqsjczyw' || this.tpls[tplDataIndex].mid == 'baqsjczywv3') {
            values[tplDataIndex] = {
              ...values[tplDataIndex],
              ...this.models
            }
          }

          if (this.tpls[tplDataIndex].mid == 'baqsjczv3' || this.tpls[tplDataIndex].mid == 'baqsjczqxv3' || this.tpls[tplDataIndex].mid == 'baqsjczywv3') {
            disposeTpl.form_data = values[tplDataIndex]
          }
          this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
        }
        // let secUserId = 0;
        // if (parseInt(this.nextUserId) != parseInt(this.leaderID)) {
        //   secUserId = parseInt(this.leaderID);
        // }
        const lastApplyIds = []
        if (this.lastDisposeIds.length > 0) {
          for (const history of this.circulationHistoryList) {
            if (history.state == '职能部门处置' && history.status == 0) {
              this.lastDisposeIds = this.lastDisposeIds.filter(item => item !== history.processor_id)
            }
            if (history.state == '职能部门处置' && history.status == 1) {
              lastApplyIds.push(history.processor_id)
            }
          }
          this.leaderID = this.mergeAndDedupeArrays(this.lastDisposeIds, this.leaderID)
        }
        let isAssign = 0
        if (this.processStructureValue.workOrder.current_state_name ==
          '职能部门处置中' && item.label == '退回') {
          isAssign = 1
        }

        if (this.processStructureValue.workOrder.current_state_name ==
          '医务科反馈' && item.label == '反馈') {
          for (const tplDataIndex in this.tpls) {
            if (this.tpls[tplDataIndex].mid == 'baqsjczv3') {
              const cz_qtysxg = [] // 字符串
              let cz_ybrysxg = []
              let cz_ygtxgys = []
              let cz_ygzztlcsjxg = []
              let cz_yyggrysxg = []
              const cz_yyggrysxgqt = [] // 字符串
              const yqssmc = [] // 字符串
              const yqssxlh = [] // 字符串
              for (const disposetpl of this.processStructureValue.disposetpls) {
                if (disposetpl.form_data.cz_qtysxg) {
                  cz_qtysxg.push(disposetpl.form_data.cz_qtysxg)
                }
                if (disposetpl.form_data.cz_ybrysxg) {
                  cz_ybrysxg = [...cz_ybrysxg, ...disposetpl.form_data.cz_ybrysxg]
                }
                if (disposetpl.form_data.cz_ygtxgys) {
                  cz_ygtxgys = [...cz_ygtxgys, ...disposetpl.form_data.cz_ygtxgys]
                }
                if (disposetpl.form_data.cz_ygzztlcsjxg) {
                  cz_ygzztlcsjxg = [...cz_ygzztlcsjxg, ...disposetpl.form_data.cz_ygzztlcsjxg]
                }
                if (disposetpl.form_data.cz_yyggrysxg) {
                  cz_yyggrysxg = [...cz_yyggrysxg, ...disposetpl.form_data.cz_yyggrysxg]
                }
                if (disposetpl.form_data.cz_yyggrysxgqt) {
                  cz_yyggrysxgqt.push(disposetpl.form_data.cz_yyggrysxgqt)
                }
                if (disposetpl.form_data.yqssmc) {
                  yqssmc.push(disposetpl.form_data.yqssmc)
                }
                if (disposetpl.form_data.yqssxlh) {
                  yqssxlh.push(disposetpl.form_data.yqssxlh)
                }
              }
              this.tpls[tplDataIndex].tplValue.cz_qtysxg = cz_qtysxg.join(',')
              this.tpls[tplDataIndex].tplValue.cz_ybrysxg = Array.from(new Set(cz_ybrysxg))
              this.tpls[tplDataIndex].tplValue.cz_ygtxgys = Array.from(new Set(cz_ygtxgys))
              this.tpls[tplDataIndex].tplValue.cz_ygzztlcsjxg = Array.from(new Set(cz_ygzztlcsjxg))
              this.tpls[tplDataIndex].tplValue.cz_yyggrysxg = Array.from(new Set(cz_yyggrysxg))
              this.tpls[tplDataIndex].tplValue.cz_yyggrysxgqt = cz_yyggrysxgqt.join(',')
              this.tpls[tplDataIndex].tplValue.yqssmc = yqssmc.join(',')
              this.tpls[tplDataIndex].tplValue.yqssxlh = yqssxlh.join(',')
            }
          }
        }

        if (item.source ==
          'userTask1714919156456' && item.label == '提交') {
          // 如果职能部门已审批的数量不等于当前需要审批的数量就不能跳转到反馈节点，需要回到职能部门审批继续
          console.log(this.leaderID)
          console.log(lastApplyIds)
          if (this.leaderID.length > 0 && lastApplyIds.length != this.leaderID.length) {
            if (item.label == '提交' && item.target == 'userTask1714837926130') {
              item.target = 'userTask1714837845689'
              item.label = '再分配'
            }
          }
        }

        handleWorkOrder({
          tasks: this.processStructureValue.process.task,
          source_state: this.processStructureValue.workOrder.current_state,
          target_state: item.target,
          circulation: item.label,
          flow_properties:
            item.flowProperties === undefined
              ? 2
              : parseInt(item.flowProperties),
          work_order_id: parseInt(this.workOrderId),
          remarks: this.remarks,
          is_exec_task: item.isExecuteTask,
          tpls: this.tpls,
          projectNo: this.ruleForm.projectNo,
          select_user_id: this.leaderID,
          self_data: this.sjpg_slot_form,
          is_assign: isAssign
        }).then(async response => {
          if (response.code === 200) {
            if (this.processStructureValue.workOrder.current_state_name ==
              '职能部门处置中' && item.label == '处置') {
              await createDisposeTpl(disposeTpl)
            }
            this.remarkVisible = false
            this.$router.push({ path: '/baqsj/upcoming', query: {}})
          }
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.process-header {
  height: 50px;

  .title {
    font-size: 25px;
    font-weight: 600;
  }

  .sub-title {
    font-size: 19px;
    vertical-align: bottom;
    padding-left: 10px;
    color: #555;
  }
}

.history-box {
  border-radius: 15px;
  background: #fff;

  .line {
    height: 22px;
    width: 5px;
    background: #277fd6;
  }
}

.empty-time {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;

  img {
    width: 200px;
  }
}

::v-deep .el-input__inner {
  color: #277fd6 !important;
}

::v-deep .el-textarea__inner {
  color: #277fd6 !important;
}
</style>
